<template>
  <div class="index-box d-flex" ref="index">
    <div class="leftBox" :style="{'width': leftTreeShow?'200px':'0px'}">
      <div class="tree-box">
        <el-tree :data="treeList" :props="defaultProps" current-node-key="" node-key="categoryId"  default-expand-all @node-click="handleNodeClick" :expand-on-click-node="false"></el-tree>
      </div>
    </div>
    <div class="rightBox">
        <div class="table-box" >
          <div class="search" ref="search">
            <el-form :inline="true" :model="searchForm" size="small" ref="searchForm" @submit.native.prevent
              class="demo-form-inline" id="searchBox">
              <el-form-item prop="goodsCode">
                  <el-input v-model="searchForm.goodsCode" clearable placeholder="请输入商品编号"></el-input>
              </el-form-item>
              <el-form-item prop="goodsName">
                  <el-input v-model="searchForm.goodsName" clearable placeholder="请输入商品名称"></el-input>
              </el-form-item>
              <el-form-item prop="storeName">
                  <el-input v-model="searchForm.storeName" clearable placeholder="请输入商家门店名称"></el-input>
              </el-form-item>
              <el-form-item prop="auditUserName">
                  <el-input v-model="searchForm.auditUserName" clearable placeholder="请输入审核人信息"></el-input>
              </el-form-item>
              <el-form-item prop="storeCategoryId">
               <treeselect
                 v-model="searchForm.storeCategoryId"
                 :options="storeListOptions"
                 :normalizer="normalizer"
                 :show-count="true"
                 placeholder="商家类型"
               />
              </el-form-item>
              <el-form-item prop="goodsState">
                <el-select filterable clearable v-model="searchForm.goodsState" placeholder="全部上/下架">
                  <el-option label="已上架" value="1" ></el-option>
                  <el-option label="已下架" value="2" ></el-option>
                </el-select>
              </el-form-item>

              <el-form-item prop="addTime">
                <el-date-picker v-model="addTime" type="daterange" align="right" unlink-panels range-separator="至"
                  start-placeholder="添加开始日期" end-placeholder="添加结束日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions">
                </el-date-picker>
              </el-form-item>

              <el-form-item class="clearfix">
                <el-button type="primary" @click="handleSearch()" icon="el-icon-search">查询</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
              </el-form-item>

            </el-form>
          </div>
          <div class="actionBtn" ref="actionBtn">
            <div class="actionBtnLeft d-flex align-center">
              <MyLeftTreeRetract :leftTreeShow.sync="leftTreeShow"></MyLeftTreeRetract>
               <el-button type="primary" @click="handleAdd()" icon="el-icon-add" size="small" v-has="'shop:evaluate:add'">新增商品</el-button>
            </div>
            <div class="actionBtnRight">
               <MyRefresh/>

            </div>
          </div>
          <div class="table" ref="table">
            <el-table :data="dataList" style="width: 100%;" row-key="id" border :height="tableHeight"
              @sort-change="handleTablechangeSort" default-expand-all stripe v-loading="loading">
              <el-table-column prop="goodsCode" label="商品编号" v-if="!hideTableColumn.includes('number')" width="140"></el-table-column>
              <el-table-column prop="name" label="商品图片" v-if="!hideTableColumn.includes('img')">
               <template #default="scope">
                  <el-image :src="scope.row.goodsImage" fit="fill" v-image-preview="scope.row.goodsImage" class="img"></el-image>
               </template>
              </el-table-column>
              <el-table-column prop="goodsName" label="商品名称" v-if="!hideTableColumn.includes('name')" width="200">
                <template #default="scope">
                  <span class="ellipsis-item2" :title="scope.row.goodsName">{{scope.row.goodsName}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="skuStocksList[0].salePrice" label="平台售价(元)" v-if="!hideTableColumn.includes('platformFor')"  align="center" width="120"></el-table-column>
              <el-table-column prop="couponPrice" label="消费券抵扣(元)" v-if="!hideTableColumn.includes('platformFor')"  align="center" width="120"></el-table-column>
              <el-table-column prop="storeName" label="商家门店名称" v-if="!hideTableColumn.includes('shopName')" width="200" show-overflow-tooltip></el-table-column>
              <el-table-column prop="storeTypeName" label="商家类型" v-if="!hideTableColumn.includes('shopType')" align="center"></el-table-column>
               <el-table-column prop="auditUserName" label="审核人信息"  align="center"  width="120"></el-table-column>
               <el-table-column prop="goodsState" label="上/下架" v-if="!hideTableColumn.includes('upStatus')"  align="center" width="100">
                 <template #default="scope">
                     <span >{{scope.row.goodsState=='2'?'已下架':'已上架'}}</span>
                 </template>
               </el-table-column>
               <el-table-column prop="addTime" label="添加时间" v-if="!hideTableColumn.includes('shopType')" align="center"></el-table-column>
              <el-table-column prop="name" label="操作" v-if="!hideTableColumn.includes('active')" width="140" align="center" fixed="right">
                <template #default="scope">
                  <div class="verticalBtn">
                  <el-button
                    type="text"
                    icon="el-icon-s-order"
                    @click="handleGoShopDetail(scope.row)"
                  >商品详情</el-button>
                  <el-button
                    type="text"
                    icon="el-icon-document-checked"
                    @click="handleGoEvaluateList(scope.row)"
                    v-has="'shop:evaluate:evaluateList'"
                  >评价记录</el-button>
                  <el-button
                    type="text"
                    icon="el-icon-edit"
                    @click="handleEvaluate(scope.row)"
                    v-has="'shop:evaluate:goEvaluate'"
                  >去评价</el-button>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div class="page" ref="page">
             <MyPagination
               :total="total"
               :page.sync="searchForm.pageNum"
               :limit.sync="searchForm.pageSize"
               @pagination="dataInfo"
             />

          </div>
        </div>
    </div>

    <!--	选择商品	-->
    <el-dialog title="选择商品" :visible.sync="productsDialogVisible" :close-on-click-modal="false" v-dialogDrag>
      <div class="tableBox d-flex">
        <div class="leftBox" style="width: 160px;height:700px" >
            <el-tree :data="shopTypeList" node-key="categoryId" ref="tree"  current-node-key="" :props="defaultProps" default-expand-all :expand-on-click-node="false" @node-click="handleShopTypeNodeClick"></el-tree>
        </div>
        <div class="rightBox" style="flex:1">
          <div class="search-box">
              <el-form :inline="true" :model="shopDialog" size="small" ref="shopDialog" @submit.native.prevent
                class="demo-form-inline d-flex " id="searchBox"  style="flex-wrap: wrap;">
                <el-form-item prop="goodsCode" style="width:200px">
                    <el-input v-model="shopDialog.goodsCode" clearable placeholder="商品编号"></el-input>
                </el-form-item>
                <el-form-item prop="name" style="width:200px">
                    <el-input v-model="shopDialog.goodsName" clearable placeholder="商品名称"></el-input>
                </el-form-item>
                <el-form-item class="clearfix">
                  <el-button type="primary" @click="handleShopSearch()" icon="el-icon-search">搜索</el-button>
                </el-form-item>
              </el-form>
            </div>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in shopDialogList" :key="index">
            	<el-card :body-style="{ padding: '0px' }"  style="margin-bottom: 10px;">
            		<img :src="item.goodsImage" height="185" style="margin: auto;display: block;">
            		<div style="padding: 14px;">
            			<p style="margin: 0px;" class="ellipsis-item" :title="item.goodsName">{{item.goodsName}}</p>
                 <p style="margin: 0px;" class="ellipsis-item" :title="item.goodsCode">({{item.goodsCode}})</p>
            			<el-button size="small" @click="checkShop(item)" :disabled="btnLoading">选择</el-button>
            		</div>
            	</el-card>
            </el-col>
            <el-empty :image-size="200" v-if="!shopDialogList.length"></el-empty>

          </el-row>
          <MyPagination
             v-if="shopDialogList.length"
            :total="shopDialog.total"
            :page.sync="shopDialog.pageNum"
            :limit.sync="shopDialog.pageSize"
            @pagination="getShopList"
          />
        </div>
      </div>


    	<div slot="footer" class="dialog-footer">
    		<el-button size="small" @click="productsDialogVisible = false">取 消</el-button>
    	</div>
    </el-dialog>
    <!--	选择商品	-->

    <!-- 审核商品 -->
    <el-dialog title="评价" width="600px" :close-on-click-modal="false" v-dialogDrag :visible.sync="evaluateVisible" @close="evaluateVisible = false">
      <div class="evaluateBox">
        <div class="shop d-flex align-center">
          <img :src="statusRow.goodsImage" alt="" style="width: 40px;"> <span style="margin:0 10px">商品评价</span> <span><el-rate v-model="evaluateForm.scoreLevel" show-text
            :texts="['非常差', '差', '一般', '好', '非常好']"></el-rate></span>
        </div>
        <div style="margin-top:10px;">
          <el-input
            type="textarea"
            placeholder="请输入评价内容"
            v-model="evaluateForm.goodsEvaluate"
            maxlength="200"
            show-word-limit
            rows="5"
          >
          </el-input>
        </div>
        <div style="margin:10px 0">
           <MyUpMoreImg :imagePreview='imgArr'  imageLimit="9" returnType="obj" @change="imageChange($event)" ></MyUpMoreImg>
        </div>
        <div>
          <el-checkbox-group v-model="evaluateForm.anonymousFlag">
              <el-checkbox label="1">匿名评价</el-checkbox>
          </el-checkbox-group>
        </div>
        <div style="margin-top:10px;display: flex;">
          <span style="margin-right:10px">物流服务</span><el-rate v-model="evaluateForm.logisticsLevel"></el-rate>
        </div>
        <div style="margin-top:10px;display: flex;">
          <span style="margin-right:10px">服务服务</span><el-rate v-model="evaluateForm.serviceLevel"></el-rate>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="evaluateVisible = false" size="small">取 消</el-button>
        <el-button type="primary" @click="handleSubmitEvaluate" size="small" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 审核商品 -->

  </div>
</template>

<script>
  import common from '@/api/api';
  import { evaluationManagementList, goodsQuerylist,addToSelfAssessment,addEvaluation } from '@/api/getData';
  import option from '../../common/option.js';
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  export default {
     components: { Treeselect },
    data() {
      return {
        loading: false,
        btnLoading: false,
        leftTreeShow:true,
        shopTypeList:[],//商家类型列表
        auditList:[],
        memberList:[],
        tableColumn:[],
        hideTableColumn:[],/*自定义表格列需要隐藏的*/
        tableColumnType:'staffManagement',/*自定义表格列类型传参*/
        addTime:[],
        searchForm: {
          goodsCategoryId:'',
          goodsCode:'',
          goodsName:'',
          storeName:'',
          auditUserName:'',
          storeCategoryId:undefined,
          levelId:'',
          auditState:"",
          goodsState:'',

          pageNum: 1,
          pageSize: 20,
        },
        total: 0,
        treeList: [],
        storeListOptions:[],//商家门店
        tableHeight:400,//table 高度
        dataList:[],
        defaultProps: {
           children: 'children',
           label: 'name'
        },
        multipleSelection: '',
        auditVisible:false,
        dialogTitle:'',
        user: {
          goodsId: '',
          auditState :'',
          auditRemark:''
        },
        rules: {
          auditState: [{required: true, message: '请选择审核状态',trigger: 'blur'}],
        },

        bannerImg:'',
        shopDialog:{
          goodsCode:"",
          goodsName:'',
          goodsCategoryId: '',
          storeName:'',
          parentCategoryId:'',
          total:0,
          pageNum:1,
          pageSize:10,
        },
        shopDialogList:[],
        productsDialogVisible:false,
        shopTypeList:[],

        evaluateVisible:false,
        statusRow:{},
        evaluateForm:{
          goodsId:'',
          scoreLevel:'',
          goodsEvaluate:'',
          attachmentIds:'',
          pictureFlag:'',
          anonymousFlag:false,

          logisticsLevel:"",
          serviceLevel:'',
        },
        imgArr:[]
      }
    },
    computed: {
      pickerOptions: () => {
        return option.pickerOptions;
      }
    },
    mounted() {
      this.getSelect();
      this.dataInfo();
      this.$nextTick(() => {
          this.tableHeight = this.$refs.index.offsetHeight - this.$refs.search.offsetHeight - this.$refs.actionBtn.offsetHeight - this.$refs.page.offsetHeight - 55;
      })
    },
    methods: {
      handleGoEvaluateList(row){
          this.$router.push({path:'/shop/evaluateList',query:{goodsId:row.goodsId}});
      },
      imageChange(path, name) {
        let arr = [];
        for(let i=0;i<path.length;i++){
          arr.push(path[i].attachmentId)
        }
        this.evaluateForm.attachmentIds = arr.join(',');
        if(path.length){
          this.evaluateForm.pictureFlag = 2
        }else{
          this.evaluateForm.pictureFlag = 1
        }
      },
      handleEvaluate(row){
        this.statusRow = row;
        this.evaluateForm = {
          goodsId:row.goodsId,
          scoreLevel:0,
          goodsEvaluate:'',
          attachmentIds:'',
          pictureFlag:'',
          anonymousFlag:false,

          logisticsLevel:0,
          serviceLevel:0,
        }
        this.evaluateVisible = true;
      },
      async checkShop(item){/*选中商品*/
        try {
          this.statusRow = item;
           this.loading = true;
           this.btnLoading = true;
           const result = await addToSelfAssessment({goodsId:this.statusRow.goodsId});
           if (result.code == 200) {
              this.$message.success('成功');
             this.productsDialogVisible = false;
             this.innerVisible = false
             this.dataInfo();
           } else {
             this.$message.error(result.msg);
           }
           this.loading = false;
           this.btnLoading = false;
         } catch (err) {
           console.log(err)
         }
      },
      /** 弹框商品类型树节点点击事件 **/
      handleShopTypeNodeClick(data){
        this.shopDialog.goodsCategoryId =  data.categoryId;
        this.shopDialog.parentCategoryId = data.parentId;
        this.getShopList();
      },
      handleAdd(){
          this.productsDialogVisible = true;
          this.getCategoryDetails({categoryKey:'product_category'})
          .then(res=>{
            this.shopTypeList = [{
              categoryId:'',
              children: res.data,
              name: "商品分类",
            }];
          })
          this.getShopList();
      },
      handleShopSearch(){
        this.shopDialog.pageNum = 1;
         this.getShopList();
      },
      async getShopList(){
        try {
          this.dialogLoading = true;
          let result = await goodsQuerylist(this.shopDialog);

          if (result.code == 200) {
            this.shopDialog.total = result.total;
            this.shopDialogList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.dialogLoading = false;
        } catch (err) {
          this.dialogLoading = false;
          console.log(err)
        }
      },
      async dataInfo() {
        try {
          let data = this.addDateRange(this.searchForm, this.addTime, 'addTimeStart', 'addTimeEnd');
          this.loading = true;
          const result = await evaluationManagementList(data);
          if (result.code == 200) {
            this.total = result.total;
            this.dataList = result.rows;
          } else {
            this.$message.error(result.msg);
          }
          this.loading = false;
        } catch (err) {
          this.loading = false;
          console.log(err)
        }
      },
      handleEdit(row){
        this.$router.push({path:'/shop/editShop',query:{goodsType:row.goodsType,goodsId:row.goodsId,storeId:row.storeId,levelId:row.levelId}});
      },
      getSelect() {
        this.getCategoryDetails({categoryKey:'product_category'})/*左边 商品分类*/
        .then(res=>{
          this.treeList = [{
            categoryId: '',
            children: res.data,
            name: "商品分类",
          }];
        })
        this.getCategoryDetails({categoryKey:'stores_category'})/* 商家类型*/
        .then(res=>{
          this.storeListOptions = res.data;
        })
      },
      handleGoShopDetail(row){
         this.$router.push({path:'/shop/shopDetails',query:{goodsId:row.goodsId}});
      },
      handleAudit(row){
        this.dialogTitle = '商品审核';
        this.user.goodsId  = row.goodsId;
        this.user.auditState = '';
        this.user.auditRemark = '';
        this.auditVisible = true;
      },
      resetQuery() {
        this.addTime = [];
        this.resetForm("searchForm");
        this.dataInfo();
      },
      /** 表格排序 **/
      handleTablechangeSort (val) {
          if(val.order){
            let sortArr = [];
            sortArr.push(val.prop);
            sortArr.push(val.order);
            this.searchForm.sort = sortArr.join(',');
          }else{
            this.searchForm.sort = '';
          }
          this.dataInfo();
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.categoryId,
          label: node.name,
          children: node.children
        };
      },
      handleSubmitEvaluate(formName) {
        let data = JSON.parse(JSON.stringify(this.evaluateForm));
        if(!data.anonymousFlag){
          data.anonymousFlag = '2'
        }else{
           data.anonymousFlag = '1'
        }
        if(!data.scoreLevel){
          this.$message.warning('请给商品打分');
          return;
        }else if(!data.goodsEvaluate){
          this.$message.warning('请填写商品评价');
          return;
        }else if(!data.logisticsLevel){
          this.$message.warning('请给物流服务打分');
          return;
        }else if(!data.serviceLevel){
          this.$message.warning('请给服务态度打分');
          return;
        }
        this.btnLoading = true;
        addEvaluation(data).then((result) => {
          if (result.code == 200) {
            this.$message.success(result.msg);
            this.evaluateVisible = false;
            this.dataInfo();
          } else {
            this.$message.error(result.msg);
          }
          this.btnLoading = false;
        });
      },
      handleSearch() {
        this.page = 1;
        this.dataInfo();
      },
      resetFormDialog(formName) {
        this.$refs[formName].resetFields();
      },
      handleNodeClick(data){/*树节点点击事件*/
       this.searchForm.goodsCategoryId = data.categoryId;
       this.searchForm.page = 1;
       this.dataInfo();
      },
    }
  }
</script>

<style scoped lang="scss">
  .index-box{
    padding:0px!important;
    margin-left:0px;
  }
  .tree-box /deep/ .el-tree-node{
     background: #D8E4DD;
  }
  .tree-box> /deep/ .el-tree>.el-tree-node{
    padding:10px;
  }
  .tree-box> /deep/ .el-tree .is-current{
    background:#fff;
  }
  .table-box{
    padding:15px
  }
  .down{
    color: #909399;
    cursor: pointer;
    text-decoration:underline;
  }
  .down:hover{
    color: #a6a9ad;
  }
  .up{
    color:#61997A;
    cursor: pointer;
    text-decoration:underline;
  }
  .up:hover{
    color:#81ad95;
  }
</style>
